<template>
	<view class="wrap ">
		<js-error mode="bottom" ref="jsError"></js-error>
		<xw-scan></xw-scan>
		<view style="background-color: #fff;padding: 10px;">
			<view style="display: flex;justify-content: space-between;align-items: center;" class="margin-bottom-lg">
				<view style="font-size: 50rpx;">
					<u-icon name="grid" size="40" style="margin: 0 5px;"></u-icon>
					{{model.name}}
				</view>
				<view style="font-size: 25px;">
					<dictLabel style="margin-left: 10px;" :value="model.machineStatus" dict-type="m8_machine_status">
					</dictLabel>
				</view>
			</view>
			<view style="margin-left: 5px;font-size: 40rpx;">
				<view class="margin-bottom-lg">
					图名：{{model.task && model.task.orderPic && model.task.orderPic.picname?model.task.orderPic.picname:''}}
				</view>
				<view class="margin-bottom-lg">
					图号：{{model.task && model.task.orderPic && model.task.orderPic.picno?model.task.orderPic.picno:''}}
				</view>
				<view style="display: flex;justify-content: space-between;" class="margin-bottom-lg">
					<view class="">
						当前工序：{{model.task && model.task.oper && model.task.oper.operName?model.task.oper.operName:''}}
					</view> 
					<u-icon @click="getData('reload')" name="reload" size="70"></u-icon>
				</view>
				
				<view class="margin-bottom-lg">
					加工进度：
					<text v-if="model.task">
						{{
					        '   加(' +
					        (model.useJgTime || '无') +
					        ') 完(' +
					        (model.task.sumQty || '无') +
					        ') '
					     }}
						<text v-if="model.task.orderPic">
							{{ '图(' + (model.task.orderPic.iqty || '无') + ')' }}
						</text>
					</text>
				</view>
				
				
				<view class="margin-bottom-lg">
					操作员：{{model.managerNames || ''}}
				</view>
				<!-- <view v-if="model.task.orderPic">
		 		<view v-if="model.task.orderPic.picname" style="margin-bottom: 10px;">
		 			图名：{{model.task.orderPic.picname || ''}}
		 		</view>
		 		<view v-if="model.task.orderPic.picno" style="margin-bottom: 10px;">
		 			图号：{{model.task.orderPic.picno || ''}}
		 		</view>
		 	</view>
		 	<view v-if="model.task.oper">
		 		<view v-if="model.task.oper.operName" style="margin-bottom: 10px;">
		 			当前工序：{{ model.task.oper.operName || ''}}
		 		</view>
		 	</view> -->
			</view>
		</view>
		<view class="flex margin-sm flex-wrap justify-between u-skeleton">
			<view class="flex bg-white padding radius " v-for="item in menuList" :key="item.menuName"
				@click="navTo(item)" style="margin-bottom: 15rpx;">
				<view class="xm-item u-skeleton-rect">
					<view class="xm-item-1">{{item.menuName}}</view>
					<view class="xm-item-2">{{item.menuTitle}}</view>
				</view>
				<image style="width: 86rpx; height: 86rpx" :src="item.menuIcon" mode="aspectFit"
					class="u-skeleton-circle" />
			</view>
		</view>
		<!-- height="80%" -->
		<u-popup v-model="show" mode="center" :mask-close-able="false" width="80%" border-radius="10">
			<view style="width: 100%;height: 100%;">
				<view
					style="width: 100%;text-align: center;padding: 10px;font-size: 18px;background: #3E97B0;color: #fff;">
					{{barCodeTitle}}
				</view>
				<view style="width: 100%;padding: 10px;">
					<u-input type="textarea" :clearable="false" placeholder="请扫描图纸和工牌" v-model="inputRef" height="400"
						maxlength="500" />
				</view>
				<view style="color: red;padding: 0 10px;min-height: 20px">
					{{tips}}
				</view>
				<view style="padding: 20rpx 40rpx;">
					<view style=" display: flex;justify-content: space-between;margin-bottom: 20rpx; ">
						<u-button style="flex: 1;margin-right: 20rpx;" plain class="btn" type="primary" @click="clearText('1')">重新扫描</u-button>
						<u-button style="flex: 1;" plain class="btn" type="primary" @click="search">扫一扫</u-button>
					</view>
					<view style=" display: flex;justify-content: space-between; ">
						<u-button style="flex: 1;margin-right: 20rpx;" type="error" plain class="btn" @click="cancel">关闭</u-button>
						<u-button style="flex: 1;" plain class="btn" type="success" @click="endScan('do')">结束扫描</u-button>
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		hasPermission
	} from '@/common/fire.js'
	import {
		mapState
	} from 'vuex';
	import dictLabel from "@/components/dictLabel.vue";
	export default {
		components: {
			dictLabel,
		},
		data() {
			return {
				tips: '',
				checkData:{},
				queryData: {
					funcType: ''
				},
				barCodeTitle: '',
				barCode: '',
				inputRef: '',
				enterCount: 0,
				show: false,
				model: {},
				selectList: [],
				stringPermissions: [],
				imgList: [{
						image: '/static/jeesite/banner/1.png'
					},
					{
						image: '/static/jeesite/banner/3.png'
					},
					{
						image: '/static/jeesite/banner/2.jpg'
					},
					{
						image: '/static/jeesite/banner/4.png'
					},
				],
				todoCount: 0,
				// flag: hasPermission('app:proj:weekly:pmWeekly:edit'),
				menuList1: [],
				menuList: [

					{
						extend: {
							extendS2: 'menue:ktnw:djh'
						},
						// menuIcon: '/static/image/zfgs/index/tzsj.png',
						menuIcon: '/static/image/sj.png',
						menuName: '图纸上机',
						menuTitle: '',
						funcType: 'shangJi',
						id: '1',
					},
					{
						extend: {
							extendS2: 'menue:ktnw:jhjl'
						},
						// menuIcon: '/static/image/zfgs/index/szjc.png',
						menuIcon: '/static/image/xj.png',
						menuName: '图纸下机',
						menuTitle: '',
						funcType: 'xiaJi',
						id: '2',
					},
					{
						extend: {
							extendS2: 'menue:ktnw:yjh'
						},
						// menuIcon: '/static/image/zfgs/index/jcqr.png',
						menuIcon: '/static/image/ksjg.png',
						menuName: '开始加工',
						menuTitle: '',
						funcType: 'beginWork',
						id: '3',
					},
					{
						extend: {
							extendS2: 'menue:ktnw:ckdd'
						},
						// menuIcon: '/static/image/zfgs/index/ccqr.png',
						menuIcon: '/static/image/jsjg.png',
						menuName: '结束加工',
						menuTitle: '',
						funcType: 'endWork',
						id: '4',
					},

					{
						extend: {
							extendS2: 'menue:ktnw:qtsj'
						},
						// menuIcon: '/static/image/zfgs/index/icon@2x(7).png',
						menuIcon: '/static/image/tzsj.png',
						menuName: '通知首检',
						menuTitle: '',
						funcType: 'notifyFirstCheck',
						id: '5',
					},
					{
						extend: {
							extendS2: 'menue:ktnw:sjjl'
						},
						// menuIcon: '/static/image/zfgs/index/icon@2x(12).png',
						menuIcon: '/static/image/tsdj.png',
						// url: '/pages/ktnw/qtsj/list?busType=1',
						menuName: '调试登记',
						menuTitle: '',
						funcType: 'debug',
						id: '6',
					},

				],
			}
		},
		computed: {
			...mapState(['vuex_company']),
		},
		onShow() {
			this.getData()
			// console.log('页面开启（onLoad）广播监听事件：xwscan')
			// 开启广播监听事件
			uni.$on('xwscan', this.BroadcastScanningToObtainData)
			// this.query.pageNo = 1;
			// this.loadData();

		},
		onHide() {
			// console.log('页面销毁（onUnload）广播监听事件：xwscan')
			// 销毁广播监听事件
			uni.$off('xwscan', this.BroadcastScanningToObtainData)
		},
		onUnload() {
			// console.log('页面销毁（onUnload）广播监听事件：xwscan')
			// 销毁广播监听事件
			uni.$off('xwscan', this.BroadcastScanningToObtainData)
		},
		onLoad(e) {
			this.queryData.machineId = e.id
			
			// this.model = JSON.parse(e.item)
			// this.queryData.machineId = this.model.id
			
			uni.$on('xzgx', (e) => {
				let data = {
					...this.checkData,
					oper:e.oper,
					task:{
						taskCode:e.taskCode
					}
				}
				
				setTimeout(()=>{
					uni.navigateTo({
						url: '/pages/m8/shangJi/form',
						events: {
							Filter(data) {
							}
						},
						success: function(resq) {
							resq.eventChannel.emit('shangJi', data)
						}
					})
				},500)
			})
		},
		methods: {
			/** 发生声音*/
			sendMp3(name) {
				console.log("=====testClick=====");
				let src = '/static/jeesite/' + name + '.mp3';
				//实例化声音  
				const Audio = uni.createInnerAudioContext();
				Audio.autoplay = true;
				Audio.src = src; //音频地址  
				Audio.play(); //执行播放  
				Audio.onError((res) => {
					console.log(res.errMsg);
					console.log(res.errCode);
				});
				Audio.onPause(function() {
					console.log('end');
					Audio.destroy();
				});
			},
			getData(type){
				console.log(this.vuex_user.userCode,'====');
				let that = this
				this.$u.api.m8.machineListData({id:this.queryData.machineId}).then((res) => {
					that.model = res.list[0]
					if(type == 'reload'){
						that.$u.toast('刷新成功！');
					}
				});
			},
			cancel(){
				this.show = false;
			},
			endScan(type) {
				let that = this
				let lines = this.inputRef.split(/[(\r\n)\r\n]+/);
				lines.forEach((item, index) => {
					// 删除空项
					if (item === '') {
						lines.splice(index, 1);
					}
				});
				this.enterCount++;
				lines.forEach((item) => {
					if (item.startsWith('98-')) {
						this.queryData.barUser = item;
					} else if (item.startsWith('99-')) {
						this.queryData.barPic = item;
					} 
				});
				// this.vuex_config.deviceType === this.vuex_config.deviceTypeAPP
				if(!this.vuex_config.workScan){
					if(this.enterCount == '1' || type == 'do'){
						if (!this.queryData.barPic) {
						    this.tips = '图纸条码不正确!';
						    // this.clearText();
							// this.enterCount = 0;
							this.sendMp3('sb');
							return false;
						}
						// if (!this.queryData.barUser) {
						//     this.tips = '用户条码不正确!';
						// 	this.sendMp3('sb');
						// 	return false;
						// }
						this.$u.api.m8.checkMachineBar({
							...this.queryData,
							barUser:'98-' + this.vuex_user.userCode
						}).then((res) => {
							if(res.result == 'true' && !res.data.errorMsg){
								this.sendMp3('cg');
								if(this.queryData.funcType == 'debug'){
									uni.navigateTo({
										url: '/pages/m8/debug/form',
										events: {
											Filter(data) {
											}
										},
										success: function(resq) {
											resq.eventChannel.emit('debug', res.data)
										}
									})
								}
								
								if(this.queryData.funcType == 'notifyFirstCheck'){
									uni.navigateTo({
										url: '/pages/m8/notifyFirstCheck/form',
										events: {
											Filter(data) {
											}
										},
										success: function(resq) {
											resq.eventChannel.emit('notifyFirstCheck', res.data)
										}
									})
								}
								
								if(this.queryData.funcType == 'shangJi'){
									uni.navigateTo({
										url: '/pages/m8/machine/xzgxList',
										events: {
											Filter(data) {
											}
										},
										success: function(resq) {
											resq.eventChannel.emit('shangJi', res.data)
										}
									})
								}
								
								if(this.queryData.funcType == 'xiaJi'){
									uni.navigateTo({
										url: '/pages/m8/xiaJi/form',
										events: {
											Filter(data) {
											}
										},
										success: function(resq) {
											resq.eventChannel.emit('xiaJi', res.data)
										}
									})
								}
								
								if(this.queryData.funcType == 'beginWork'){
									uni.navigateTo({
										url: '/pages/m8/beginWork/form',
										events: {
											Filter(data) {
											}
										},
										success: function(resq) {
											resq.eventChannel.emit('beginWork', res.data)
										}
									})
								}
								
								if(this.queryData.funcType == 'endWork'){
									uni.navigateTo({
										url: '/pages/m8/endWork/form',
										events: {
											Filter(data) {
											}
										},
										success: function(resq) {
											resq.eventChannel.emit('endWork', res.data)
										}
									})
								}
								
								
								this.show = false;
								
							}else{
								this.sendMp3('sb');
								this.tips = res.message || res.data.errorMsg
							}
						});
					}
				}else{
					if(this.enterCount == '2' || type == 'do'){
						if (!this.queryData.barPic) {
						    this.tips = '图纸条码不正确!';
						    // this.clearText();
							// this.enterCount = 0;
							this.sendMp3('sb');
							return false;
						}
						if (!this.queryData.barUser) {
						    this.tips = '用户条码不正确!';
						    // this.clearText();
							// this.enterCount = 0;
							this.sendMp3('sb');
							return false;
						}
						this.$u.api.m8.checkMachineBar(this.queryData).then((res) => {
							if(res.result == 'true' && !res.data.errorMsg){
								this.sendMp3('cg');
								if(this.queryData.funcType == 'debug'){
									uni.navigateTo({
										url: '/pages/m8/debug/form',
										events: {
											Filter(data) {
											}
										},
										success: function(resq) {
											resq.eventChannel.emit('debug', res.data)
										}
									})
								}
								
								if(this.queryData.funcType == 'notifyFirstCheck'){
									uni.navigateTo({
										url: '/pages/m8/notifyFirstCheck/form',
										events: {
											Filter(data) {
											}
										},
										success: function(resq) {
											resq.eventChannel.emit('notifyFirstCheck', res.data)
										}
									})
								}
								
								if(this.queryData.funcType == 'shangJi'){
									uni.navigateTo({
										url: '/pages/m8/machine/xzgxList',
										events: {
											Filter(data) {
											}
										},
										success: function(resq) {
											resq.eventChannel.emit('shangJi', res.data)
										}
									})
								}
								
								if(this.queryData.funcType == 'xiaJi'){
									uni.navigateTo({
										url: '/pages/m8/xiaJi/form',
										events: {
											Filter(data) {
											}
										},
										success: function(resq) {
											resq.eventChannel.emit('xiaJi', res.data)
										}
									})
								}
								
								if(this.queryData.funcType == 'beginWork'){
									uni.navigateTo({
										url: '/pages/m8/beginWork/form',
										events: {
											Filter(data) {
											}
										},
										success: function(resq) {
											resq.eventChannel.emit('beginWork', res.data)
										}
									})
								}
								
								if(this.queryData.funcType == 'endWork'){
									uni.navigateTo({
										url: '/pages/m8/endWork/form',
										events: {
											Filter(data) {
											}
										},
										success: function(resq) {
											resq.eventChannel.emit('endWork', res.data)
										}
									})
								}
								
								
								this.show = false;
								
							}else{
								this.sendMp3('sb');
								this.tips = res.message || res.data.errorMsg
							}
						});
					}
				}
				
				
			},
			clearText(flag) {
				this.inputRef = '';
				this.enterCount = 0;
				this.queryData.barPic = ''
				this.queryData.barUser = ''
				if(flag == '1'){
					this.tips = ''
				}
			},
			navTo(item) {
				if(item.funcType == 'debug' && this.model.machineStatus != '3'){
					this.$refs.jsError.showError("", "当前机床不可调试!", "error");
					return
				}
				
				if(item.funcType == 'notifyFirstCheck' && (this.model.firstCheckStatus !='0' || (this.model.machineStatus != '1' && this.model.machineStatus != '3'))){
					this.$refs.jsError.showError("", "当前机床不可发送首检通知!", "error");
					return
				}
				
				this.show = true;
				this.enterCount = 0;
				this.tips = '';
				this.barCodeTitle = item.menuName;
				this.queryData.funcType = item.funcType
				this.queryData.barPic = ''
				this.queryData.barUser = ''
				this.inputRef = '';
				
				if(this.vuex_config.deviceType === this.vuex_config.deviceTypeAPP){
					this.search()
				}
			},
			BroadcastScanningToObtainData(res) {
				//获取扫描到的条形码
				let barcode = res.code

				//判断条形码长度是否大于3
				if (barcode.length > 3) {
					//去除换行符
					let newString = barcode.replace('\n;', '');

					this.barCode = newString + '\n';;
					
					this.confirm()
					//将换行符分割成数组
					// const allItems = newString.split('\n');
					// 	//遍历数组，将每一项添加到arr中
					// 	for(let i = 0;i<allItems.length;i++){
					// 		this.arr.push({
					// 			"content":allItems[i],
					// 			"remarks":this.remarks
					// 		})
					// 	}
				}
			},
			confirm() {
				let _this = this;
				this.inputRef += this.barCode
				
				this.endScan()
				setTimeout(() => {
					this.barCode = ''
				}, 500)
			},
			search() {
				let _that = this;
				uni.scanCode({
					scanType: ["barCode", "qrCode"],
					// onlyFromCamera: true,
					success: function(res) {
						console.log("条码类型：" + res.scanType);
						console.log("条码内容：" + res.result);
						_that.barCode = res.result + '\n';
						_that.confirm()
						if(_that.vuex_config.workScan && _that.enterCount <2){
							setTimeout(()=>{
								_that.search()
							},500)
						}
					},
				});
			},
		}
	}
</script>

<style scoped lang="scss">
	.cu-item {
		width: 41% !important;
		height: 90px;
	}

	.cuIcon-cardboardfill {
		margin-top: 20px !important;
	}

	.xm-title {
		border-radius: 20rpx;
		font-size: 36rpx;
		background-color: #fff;
		// background-image: url("/static/image/zfgs/index/icon@2x.png");
		// background-repeat: no-repeat;
		// background-size: 38rpx 42rpx;
		// background-position: 10rpx 10rpx;
		position: relative;

		.xm-title-p1 {
			color: #999999;
			font-size: 36rpx;
			line-height: 40rpx;
			margin-bottom: 8rpx;
		}

		.xm-title-p2 {
			color: #3d3d3d;
			line-height: 48rpx;
		}

		.xm-title-img {
			width: 38rpx;
			height: 42rpx;
			position: absolute;
			top: 0;
			right: 32rpx;
		}
	}

	.xm-item-1 {
		font-size: 42rpx;
		color: #3d3d3d;
		line-height: 40rpx;
		position: relative;
		margin-bottom: 26rpx;
	}

	.xm-item-1::after {
		content: "";
		display: inline-block;
		position: absolute;
		width: 32rpx;
		height: 4rpx;
		background-color: #bbbbbb;
		bottom: -16rpx;
		left: 0;
	}

	.xm-item {
		width: 200rpx;
	}

	.radius {
		border-radius: 20rpx;
	}

	.xm-item-2 {
		font-size: 34rpx;
		color: #999999;
	}
</style>